package edu.fdzc.big_event.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import edu.fdzc.big_event.mapper.ArticleMapper;
import edu.fdzc.big_event.pojo.Article;
import edu.fdzc.big_event.pojo.PageBean;
import edu.fdzc.big_event.pojo.Result;
import edu.fdzc.big_event.service.ArticleService;
import edu.fdzc.big_event.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public void add(Article article) {
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());

        Map<String,Object> claims = ThreadLocalUtil.get();
        Integer id = (Integer) claims.get("id");

//        article.setCategoryId(id);
        article.setCreateUser(id);
        articleMapper.add(article);

    }

    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        //创建PageBean实体
        PageBean<Article> pageBean = new PageBean<>();
        //开启分页查询PageHelper
        PageHelper.startPage(pageNum, pageSize);
        //调用mapper
        Map<String,Object> claims = ThreadLocalUtil.get();
        Integer id = (Integer) claims.get("id");
        List<Article> as =  articleMapper.list(id,categoryId,state);
        Page<Article> page = (Page<Article>) as;
        //将数据填充到PageBean中

//        Page<Article> page = PageHelper.startPage(pageNum, pageSize).doSelectPage(() -> {
//            Map<String, Object> claims = ThreadLocalUtil.get();
//            Integer userId = (Integer) claims.get("id");
//            articleMapper.list(userId, categoryId, state); // 确保这里执行的是分页查询
//        });

        pageBean.setTotal(page.getTotal());
        pageBean.setItems(page.getResult());
        return pageBean;
    }

    @Override
    public Article findById(Integer id) {
       return articleMapper.findById(id);
    }

    @Override
    public void update(Article article) {
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.update(article);
    }

    @Override
    public void delete(Integer id) {
        articleMapper.delete(id);
    }


}
